package top.tenebrous.yzl.handler.sechub;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.tenebrous.yzl.basic.constant.Constants;
import top.tenebrous.yzl.chain.AbstractJesticChainHandler;
import top.tenebrous.yzl.context.JesticContext;
import top.tenebrous.yzl.context.JesticTask;
import top.tenebrous.yzl.context.Response;
import top.tenebrous.yzl.entity.JesticServer;
import top.tenebrous.yzl.instance.AbstractInstanceContext;
import top.tenebrous.yzl.model.request.JestcSechubRequst;
import top.tenebrous.yzl.model.response.JestcSechubResponse;
import top.tenebrous.yzl.utils.AESCodec;
import top.tenebrous.yzl.utils.Base64Util;

/**
 * @author yazhang6
 */
@Slf4j
public class JesticSechubHandler extends AbstractJesticChainHandler<JestcSechubRequst, JestcSechubResponse> {

    int order;

    @SneakyThrows
    @Override
    public void handler(JesticContext<? extends JesticTask, ? extends Response> context) {
        JestcSechubRequst request = (JestcSechubRequst) context.getRequest();
        JestcSechubResponse response = (JestcSechubResponse) context.getResponse();
        JesticServer jesticServer = context.getJesticServer();
        log.info("JesticSechubHandler.handler:[{}]", request.getStatus());

        // 对加密数据进行base64解密
        String data = Base64Util.decode(request.getPwd());
        String result;
        if (Constants.INT_ONE == request.getType()) {
            // 加密
            result = AESCodec.encrypt(data, jesticServer.getServerKey());
        } else {
            // 解密
            result = AESCodec.decrypt(data, jesticServer.getServerKey());
        }

        response.setData(result);

        if (null != nextHandler) {
            nextHandler.handler(context);
        } else {
            request.end();
        }

    }

    @Override
    public int order(String taskType) {
        return this.order;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    @Override
    public AbstractJesticChainHandler<JestcSechubRequst, JestcSechubResponse> setOrder(int order) {
        this.order = order;
        return this;
    }
}
